// 蜂窝蜜造平台生成代码，此文件只生成一次，不需要添加到 .beeignore

package com.fowo.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.amazon.spapi.api.FbaInboundApi;
import com.amazon.spapi.model.fulfillmentinbound.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.controller.shipment.entity.FbaShipmentVoD;
import com.fowo.api.controller.shipment.entity.InboundShipmentPlanD;
import com.fowo.api.controller.shipment.entity.InboundShipmentPlanItemD;
import com.fowo.api.controller.shipment.entity.InboundShipmentPlanListD;
import com.fowo.api.entity.*;
import com.fowo.api.model.fba.shipment.FbaShipmentVo;
import com.fowo.api.model.fba.shipment.product.FbaShipmentProductItemVo;
import com.fowo.api.model.fba.shipment.product.FbaShipmentProductSearchParamPo;
import com.fowo.api.model.ship.plans.shipment.ShipPlansShipmentVo;
import com.fowo.api.model.shop.info.ShopInfoVo;
import com.fowo.api.service.ShipPlansService;
import com.fowo.api.service.ShipPlansShipmentService;
import com.fowo.api.service.ShipPlansSubService;
import com.fowo.api.syncAmazon.api.ShipmentService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.util.LocalDateUtils;
import liquibase.pro.packaged.S;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * fba货件 服务实现类
 */
@Service
public class FbaShipmentServiceImpl extends FbaShipmentBaseServiceImpl {

    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private ShipmentService shipmentService;
    @Resource
    private ShipPlansShipmentServiceImpl shipPlansShipmentService;
    @Resource
    private ShipPlansServiceImpl shipPlansService;
    @Resource
    private ShipPlansSubServiceImpl shipPlansSubService;
    @Resource
    private ProductServiceImpl productService;


    @Override
    public FbaShipmentVo getVoById(Long id) throws Exception {
        FbaShipmentVo voById = super.getVoById(id);
        ShopInfoVo voById1 = shopInfoService.getVoById(voById.getShop());
        voById.setShopName(voById1!=null?voById1.getShopName():"");
        return voById;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long create(FbaShipmentVo model) throws Exception {
        List<FbaShipmentProductItemVo> list = model.getList();
        list.stream().forEach(item -> {
            item.setQuantityShippedLocal(0);
            item.setQuantityReceived(0);
            item.setShenFaDifference(0);
            item.setShenShouDifference(0);
            item.setShouFaDifference(0);
        });
        ShopInfo byId = shopInfoService.getById(model.getShop());
        model.setCountry(byId.getCountry());
        Long aLong = super.create(model);
        return aLong;
    };

    @Transactional(rollbackFor = Exception.class)
    public Long create2(FbaShipmentVoD model) throws Exception {
        //亚马逊货件返回的计划
        InboundShipmentPlanList inboundShipmentPlanList = model.getInboundShipmentPlanList();
        InboundShipmentPlanListD inboundShipmentPlanListD=model.getInboundShipmentPlanListD();
        Map<String,String> shipmentNameMap=new HashMap<>();
        for(int i=0;i<inboundShipmentPlanListD.size();i++){
            shipmentNameMap.put(inboundShipmentPlanListD.get(i).getShipmentId(),inboundShipmentPlanListD.get(i).getShipmentName());
        }
        Map<String, String> inboundShipment=null;
        try{
            inboundShipment= shipmentService.createInboundShipment(model.getShop(), inboundShipmentPlanList,shipmentNameMap);
        }catch (Exception e) {
            Assert.isTrue(false,"请求亚马逊接口失败:"+e.getMessage());
        }
        //创建货件
        //循环map
        for(String key:inboundShipment.keySet()){
            String s = inboundShipment.get(key);
            InboundShipmentPlan inboundShipmentPlan = inboundShipmentPlanList.stream().filter(x -> x.getShipmentId().equals(s)).collect(Collectors.toList()).get(0);
            FbaShipmentVo shipment = createShipment(inboundShipmentPlan, model,shipmentNameMap);
            Long aLong = super.create(shipment);
        }
        return (long)0;
    }

    private FbaShipmentVo createShipment(InboundShipmentPlan inboundShipmentPlan,FbaShipmentVoD model,Map<String,String> shipmentNameMap)throws Exception {
        //shippingAddress
        FbaShipmentVo model2=new FbaShipmentVo();
        BeanUtils.copyProperties(model,model2);
        model2.setShipmentName(shipmentNameMap.get(inboundShipmentPlan.getShipmentId()));
        //货件号
        model2.setShipmentId(inboundShipmentPlan.getShipmentId());
        model2.setShipmentStatus("WORKING");
        model2.setWorkingTime(new Date());
        model2.setCreateTime(new Date());//packingType  sendAddress

//        model2.setPackingType(inboundShipmentPlan.getLabelPrepType());
        model2.setDestinationFulfillmentCenterId(inboundShipmentPlan.getDestinationFulfillmentCenterId());
        model2.setShippingAddress(montageAddress(inboundShipmentPlan));
//        inboundShipmentPlan.getShipToAddress();
        InboundShipmentPlanItemList items = inboundShipmentPlan.getItems();
        List<FbaShipmentProductItemVo> list=new ArrayList<>();
        for(int i=0;i<items.size();i++){
            FbaShipmentProductItemVo fbaShipmentProductItemVo2=new FbaShipmentProductItemVo();
            InboundShipmentPlanItem inboundShipmentPlanItem = items.get(i);
            FbaShipmentProductItemVo fbaShipmentProductItemVo = model.getList().stream().filter(x -> x.getMsku()
                    .equals(inboundShipmentPlanItem.getSellerSKU())).collect(Collectors.toList()).get(0);
            BeanUtils.copyProperties(fbaShipmentProductItemVo,fbaShipmentProductItemVo2);
            //amountDeclared
            fbaShipmentProductItemVo2.setAmountDeclared(inboundShipmentPlanItem.getQuantity());
            Product product = productService.getOne(Wrappers.<Product>query().lambda().eq(Product::getSku, fbaShipmentProductItemVo.getSku()));
            fbaShipmentProductItemVo2.setProductName(product.getId());
            fbaShipmentProductItemVo2.setQuantityShippedLocal(0);
            fbaShipmentProductItemVo2.setQuantityReceived(0);
            fbaShipmentProductItemVo2.setLabel(fbaShipmentProductItemVo.getTitle());
            fbaShipmentProductItemVo2.setShenFaDifference(0);
            fbaShipmentProductItemVo2.setShenShouDifference(0);
            //设置发货店铺和发货店铺的fnsku
            fbaShipmentProductItemVo2.setFnskuId(fbaShipmentProductItemVo.getFnskuId());
            fbaShipmentProductItemVo2.setShopid(fbaShipmentProductItemVo.getShopid());
            //planShioment计划发货量
            fbaShipmentProductItemVo2.setPlanShioment(fbaShipmentProductItemVo.getPlanShioment());
            fbaShipmentProductItemVo2.setShouFaDifference(0);
            //获取发货计划子表
            ShipPlansSub shipPlansSub = shipPlansSubService.getOne(Wrappers.<ShipPlansSub>query().lambda()
                    .eq(ShipPlansSub::getOrderSn, fbaShipmentProductItemVo.getShipmentPlanSn()));
            if(fbaShipmentProductItemVo.getShipmentPlanSn()!=null){
//                if(inboundShipmentPlanItem.getQuantity().intValue()>=fbaShipmentProductItemVo.getPlanShioment().intValue()){
                    //发货计划的id
                    shipPlansSub.setState("1");
                    shipPlansSub.setGenerateshipment("1");//已经生成
                    shipPlansSubService.updateById(shipPlansSub);
//                }
            }
            list.add(fbaShipmentProductItemVo2);
            //判断是否关联了发货计划 shipmentPlanSn
            if(fbaShipmentProductItemVo.getShipmentPlanSn()!=null){
                associationShipmentPlanSn(fbaShipmentProductItemVo,inboundShipmentPlan.getShipmentId(),shipPlansSub);
                //判断是否全部关联
                Long shipPlansIds= shipPlansSub.getParentShipPlans();
                isCompleted(shipPlansIds);
            }
        }
        ShopInfo byId = shopInfoService.getById(model2.getShop());
        model2.setCountry(byId.getCountry());
        model2.setList(list);
        return model2;
    }
    @DataActivity(action = SysDataActivityAction.Del)
    @Override
    public boolean delete(Long id) throws Exception {

        FbaShipmentVo voById = getVoById(id);
        shipmentService.deleteInboundShipment(voById);
        this.removeById(id);
        batchDeleteChilds(Collections.singletonList(id));
        //删除亚马逊后台货件

        return true;
    }
    private void isCompleted(Long shipPlansIds) {
        //判断是否完成了
        List<ShipPlansSub> list = shipPlansSubService.list(Wrappers.<ShipPlansSub>query().lambda()
                .eq(ShipPlansSub::getParentShipPlans, shipPlansIds));
        List<ShipPlansSub> collect = list.stream().filter(x ->x.getState()!=null&&x.getState().equals("1")).collect(Collectors.toList());
        if(collect.size()==list.size()){
            Long parentShipPlans=list.get(0).getParentShipPlans();
            ShipPlans byId = shipPlansService.getById(parentShipPlans);
            byId.setStatus("2");
            shipPlansService.updateById(byId);
        }
    }

    private String montageAddress(InboundShipmentPlan inboundShipmentPlan) {
        StringBuffer address=new StringBuffer();
        address.append(inboundShipmentPlan.getDestinationFulfillmentCenterId());
        address.append(",");
        address.append(inboundShipmentPlan.getShipToAddress().getAddressLine1());
        address.append(",");
        address.append(inboundShipmentPlan.getShipToAddress().getDistrictOrCounty());
        return address.toString();
    }

    private void associationShipmentPlanSn(FbaShipmentProductItemVo fbaShipmentProductItemVo,String shipmentId,ShipPlansSub shipPlansSub) throws Exception {
        ShipPlansShipmentVo model=new ShipPlansShipmentVo();
        model.setPlanId(shipPlansSub.getId());
        model.setShipmentNum(fbaShipmentProductItemVo.getAmountDeclared());
        model.setShipmentOrder(shipmentId);
        shipPlansShipmentService.create(model);
    }

}
